// 内容脚本
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "click_items") {
    const table = document.querySelector('.el-table__body-wrapper tbody');
    // 选择所有数据行中的目标单元格（跳过表头）
    const items = table.querySelectorAll('tr td.el-table_1_column_2 .cell');
    (async () => {
      for (let i = 0; i < items.length; i++) {
        await new Promise(resolve => setTimeout(resolve, i * 500));
        
        // 每次点击前重新获取元素
        const currentItem = document.querySelectorAll('tr td.el-table_1_column_2 .cell')[i];
        if (!currentItem) continue;
        
        console.log(`正在点击第 ${i + 1} 项: ${currentItem.textContent}`);
        currentItem.click();
        
        // 等待PDF页面加载
        await new Promise(resolve => setTimeout(resolve, 3000));
        
        // 获取PDF iframe地址
        const pdfIframe = document.querySelector('iframe[src*="/tools/viewer/file/"]');
        if (pdfIframe) {
          const pdfUrl = pdfIframe.src;
          const pdfId = pdfUrl.match(/file\/(\d+)/)[1];
          const downloadUrl = `https://www.jiaoyifamen.com/tools/viewer/pdf/${pdfId}`;
          
          // 发送下载请求
          chrome.runtime.sendMessage({
            action: "download_pdf",
            url: downloadUrl,
            filename: `${currentItem.textContent.trim()}.pdf`
          });
          
          // 关闭PDF页面
          window.close();
        }
      }
    })();
  }
});
